package com.example.park.ui.notifications;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.park.Protocol;
import com.example.park.R;
import com.example.park.RegisterActivity; // 导入注册页面的类
import com.example.park.TcpClient;


import org.json.JSONException;
import org.json.JSONObject;


/*
public class NotificationsFragment extends Fragment {

    private EditText usernameEditText, passwordEditText;
    private Button loginButton;
    private TextView registerPrompt;

    public NotificationsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_notifications, container, false);

        // 获取视图组件
        usernameEditText = rootView.findViewById(R.id.edit_username);
        passwordEditText = rootView.findViewById(R.id.edit_password);
        loginButton = rootView.findViewById(R.id.login_button);
        registerPrompt = rootView.findViewById(R.id.register_prompt);

        // 登录按钮点击事件
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();
                try {
                    JSONObject root = new JSONObject();
                    JSONObject message = new JSONObject();
                    message.put("username",username);
                    message.put("password",password);

                    root.put("func",2);
                    root.put("message",message);

                    String jsonString = root.toString();
                    String package_ = Protocol.Encode(jsonString);
                    TcpClient.getInstance().sendMessage(package_);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                new Thread(() -> {
                    try {
                        String response = TcpClient.getInstance().receiveMessage();
                        if (response == null || response.isEmpty()) {
                            requireActivity().runOnUiThread(() ->
                                    Toast.makeText(getActivity(), "未收到服务器响应", Toast.LENGTH_SHORT).show()
                            );
                            return;
                        }

                        StringBuilder remaining = new StringBuilder();
                        String content = Protocol.Decode(response, remaining);

                        JSONObject json = new JSONObject(content);
                        int status = json.optInt("bool", 0);

                        requireActivity().runOnUiThread(() -> {
                            if (status == 1) {
                                Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                                // 可跳转主界面，例如：
                                // Intent intent = new Intent(getActivity(), MainActivity.class);
                                // startActivity(intent);


                                //Intent intent = new Intent(getActivity(), ProfileActivity.class);
                                // 你可以在这里添加额外的用户信息到 intent 中，例如用户名和车牌号
                                // intent.putExtra("username", username);
                                // intent.putExtra("licensePlate", plate);
                                //startActivity(intent);

                               // getActivity().getSupportFragmentManager().beginTransaction()
                                //        .replace(R.id.nav_host_fragment_activity_main, new ProfileFragment())
                                 //       .commit();

                                // 结束当前登录页面，防止用户按返回键返回到登录页面
                                //requireActivity().finish();


                            } else if (status == 2) {
                                Toast.makeText(getActivity(), "不存在该用户名用户名，请重新输入", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(), "登录失败，请检查用户名或密码", Toast.LENGTH_SHORT).show();
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                        requireActivity().runOnUiThread(() ->
                                Toast.makeText(getActivity(), "接收或解析服务器数据出错", Toast.LENGTH_SHORT).show()
                        );
                    }
                }).start();
            }
        });

        // 注册提示文本点击事件
        registerPrompt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到注册页面
                Intent intent = new Intent(getActivity(), RegisterActivity.class);
                startActivity(intent);
            }
        });

        return rootView;
    }
}
*/

public class NotificationsFragment extends Fragment {

    private EditText usernameEditText, passwordEditText;
    private Button loginButton;
    private TextView registerPrompt;

    // 登录成功后显示的组件
    private TextView nicknameTextView, plateTextView;
    private Button logoutButton;

    private View rootView;
    private boolean isLoggedIn = false;
    private String currentNickname = "";
    private String currentPlate = "";

    public NotificationsFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_notifications, container, false);
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        isLoggedIn = sharedPref.getBoolean("isLoggedIn", false);
        currentNickname = sharedPref.getString("nickname", "");
        currentPlate = sharedPref.getString("plate", "");

        // 登录界面组件
        usernameEditText = rootView.findViewById(R.id.edit_username);
        passwordEditText = rootView.findViewById(R.id.edit_password);
        loginButton = rootView.findViewById(R.id.login_button);
        registerPrompt = rootView.findViewById(R.id.register_prompt);


        // 如果已经登录了，直接显示信息
        if (isLoggedIn) {
            usernameEditText.setVisibility(View.GONE);
            passwordEditText.setVisibility(View.GONE);
            loginButton.setVisibility(View.GONE);
            registerPrompt.setVisibility(View.GONE);
            showUserInfo(currentNickname, currentPlate);
        }
        else {
            loginButton.setOnClickListener(v -> {
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();

                try {
                    JSONObject root = new JSONObject();
                    JSONObject message = new JSONObject();
                    message.put("username", username);
                    message.put("password", password);
                    root.put("func", 2);
                    root.put("message", message);
                    String jsonString = root.toString();
                    String package_ = Protocol.Encode(jsonString);
                    TcpClient.getInstance().sendMessage(package_);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                new Thread(() -> {
                    try {
                        String response = TcpClient.getInstance().receiveMessage();
                        if (response == null || response.isEmpty()) {
                            requireActivity().runOnUiThread(() ->
                                    Toast.makeText(getActivity(), "未收到服务器响应", Toast.LENGTH_SHORT).show());
                            return;
                        }

                        StringBuilder remaining = new StringBuilder();
                        String content = Protocol.Decode(response, remaining);
                        JSONObject json = new JSONObject(content);
                        int status = json.optInt("bool", 0);

                        requireActivity().runOnUiThread(() -> {
                            if (status == 1) {
                                Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                                String plate = json.optString("plate","");
                                isLoggedIn = true;

                                // 保存登录状态
                                SharedPreferences preferences = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = preferences.edit();
                                editor.putBoolean("isLoggedIn", true);
                                editor.putString("nickname", username);
                                editor.putString("plate", plate);
                                editor.apply();
                                showUserInfo(username, plate);
                            } else if (status == 2) {
                                Toast.makeText(getActivity(), "用户名不存在", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(), "登录失败，请检查用户名或密码", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        requireActivity().runOnUiThread(() ->
                                Toast.makeText(getActivity(), "接收或解析服务器数据出错", Toast.LENGTH_SHORT).show());
                    }
                }).start();
            });

            registerPrompt.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), RegisterActivity.class);
                startActivity(intent);
            });
        }
        return rootView;
    }

    private void showUserInfo(String nickname, String plate) {
        isLoggedIn = true;
        currentNickname = nickname;
        currentPlate = plate;

        // 隐藏登录相关控件
        usernameEditText.setVisibility(View.GONE);
        passwordEditText.setVisibility(View.GONE);
        loginButton.setVisibility(View.GONE);
        registerPrompt.setVisibility(View.GONE);

        // 创建一个新的 LinearLayout，垂直排列
        LinearLayout layout = new LinearLayout(getContext());
        layout.setOrientation(LinearLayout.VERTICAL);  // 设置为竖直方向排列
        layout.setGravity(Gravity.CENTER_HORIZONTAL);  // 水平居中

        // 创建并设置布局参数
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        params.setMargins(0, 24, 0, 24);  // 设置上下间距

        // 创建昵称 TextView
        nicknameTextView = new TextView(getContext());
        nicknameTextView.setText("昵称：" + nickname);
        nicknameTextView.setTextSize(18);
        nicknameTextView.setLayoutParams(params);
        layout.addView(nicknameTextView);

        // 创建车牌号 TextView
        plateTextView = new TextView(getContext());
        plateTextView.setText("车牌号：" + plate);
        plateTextView.setTextSize(18);
        plateTextView.setLayoutParams(params);
        layout.addView(plateTextView);

        // 创建退出登录按钮
        logoutButton = new Button(getContext());
        logoutButton.setText("退出登录");
        logoutButton.setLayoutParams(params);
        layout.addView(logoutButton);
        logoutButton.setWidth(2000);
        logoutButton.setHeight(100);

        // 将这个 LinearLayout 添加到 rootView 中
        ((ViewGroup) rootView).addView(layout);

        logoutButton.setOnClickListener(v -> {
            currentNickname = "";
            currentPlate = "";

            // 移除控件
            ((ViewGroup) rootView).removeView(layout);

            // 显示原登录界面
            usernameEditText.setVisibility(View.VISIBLE);
            passwordEditText.setVisibility(View.VISIBLE);
            loginButton.setVisibility(View.VISIBLE);
            registerPrompt.setVisibility(View.VISIBLE);

            // 清空输入框
            usernameEditText.setText("");
            passwordEditText.setText("");

            // 清除登录相关数据
            SharedPreferences sharedPref = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.clear();  // 清除所有登录相关数据
            editor.apply();
        });
    }

}